package com.at.bigdata.spark.core.rdd.operator.transform

import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}

/**
 *
 * @author cdhuangchao3
 * @date 2023/3/19 9:52 PM
 */
object Spark20_RDD_combineByKey {

  def main(args: Array[String]): Unit = {
    // 环境准备
    val sparkConf = new SparkConf()
      .setMaster("local[*]")
      .setAppName("Operator")
    val sc = new SparkContext(sparkConf)

    // 分区内
    // 分区间
    // TODO 算子 - key - value类型
    val rdd = sc.makeRDD(List(
      ("a", 1), ("a", 2), ("b", 3),
      ("b", 4), ("b", 5), ("a", 6)
    ), 2)

    /**
     * reduceByKey
     *    combineByKeyWithClassTag[V](
     *        (v: V) => v,
     *        func,
     *        func,
     *        partitioner)
     *
     * aggregateByKey
     *    combineByKeyWithClassTag[U](
     *        (v: V) => cleanedSeqOp(createZero(), v),
     *        cleanedSeqOp,
     *        combOp,
     *        partitioner)
     *
     * foldByKey
     *    combineByKeyWithClassTag[V](
     *        (v: V) => cleanedFunc(createZero(), v),
     *        cleanedFunc,
     *        cleanedFunc,
     *        partitioner)
     *
     * combineByKey
     *    combineByKeyWithClassTag(
     *        createCombiner,       // 相同key的第一个数据处理函数
     *        mergeValue,           // 分区内处理函数
     *        mergeCombiners,       // 分区间处理函数
              partitioner, mapSideCombine, serializer)(null)
     */

    rdd.reduceByKey(_+_)  // wordcount
    rdd.aggregateByKey(0)(_+_, _+_)
    rdd.foldByKey(0)(_+_)
    rdd.combineByKey(v => v, (x:Int, v) => x+v, (x:Int, y:Int) => x+y)

  }

}
